//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package upgrade

import (
	"context"
	"fmt"

	"gitcode.com/eteam/api-server/dao"
)

const (
	SCHEAM_VERSION = uint32(3)
)

func UpgradeDb() error {
	ctx := context.Background()
	exist, err := dao.VersionDao.Exist(ctx, dao.VERSION_KEY_SCHEMA)
	if err != nil {
		return err
	}
	if !exist {
		err = dao.VersionDao.Set(ctx, dao.VERSION_KEY_SCHEMA, 1)
		if err != nil {
			return err
		}
	}
	for {
		versionItem, err := dao.VersionDao.Get(ctx, dao.VERSION_KEY_SCHEMA)
		if err != nil {
			return err
		}
		if versionItem.Version == SCHEAM_VERSION {
			return nil
		}
		err = execUpgrade(ctx, versionItem.Version)
		if err != nil {
			return err
		}
	}
}

func execUpgrade(ctx context.Context, version uint32) error {
	if version > SCHEAM_VERSION {
		return fmt.Errorf("schema version is too high")
	}
	if version == 1 {
		uper := &UpToVer2{}
		err := uper.Exec(ctx)
		if err != nil {
			return err
		}
	} else if version == 2 {
		uper := &UpToVer3{}
		err := uper.Exec(ctx)
		if err != nil {
			return err
		}
	}
	return nil
}
